package com.source.app.selenium;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.source.utils.Utils;
import com.source.utils.train.RequestUtil;

public class BuyTicket {

	/**
	 * 查询余票接口
	 */
	private final static String searchTicketsUrl = "https://train.m.jd.com/ticket/searchTickets.json";

	/**
	 * 生成订单
	 */
	private final static String submitJDOrderUrl = "http://train.m.jd.com/bookSeat/generateOrder.json";

	/**
	 * 查询占座结果
	 */
	private final static String bookResultUrl = "http://train.m.jd.com/bookSeat/bookResult.json";

	/**
	 * 确认订单
	 */
	private final static String submitOrderUrl = "https://train.m.jd.com/bookSeat/submitOrder.action";

	/**
	 * 获取优惠券列表
	 */
	private final static String couponListUrl = "https://train.m.jd.com/coupon/couponList.json";

	/**
	 * 获取乘客列表
	 */
	private final static String passengerUrl = "https://train.m.jd.com/passenger/list.json";

	/**
	 * 添加乘客 contactName=zhangsan&idCardType=1&idCardInfo=372928199409067423 身份证
	 * 1 护照 B 台湾通行证 G
	 */
	private final static String addPassengerUrl = "https://train.m.jd.com/passenger/add.json";

	/**
	 * 添加联系人
	 *
	 * contactName=%E4%B8%AD%E5%8D%8E%E9%AD%82&contactPhone=15111777871
	 */
	private final static String addContact = "https://train.m.jd.com/contact/add.json";

	public static void main(String[] args) {
		String Cookie = LoginAction.login("", "");
		String fromStationName ="北京";
		String toStationName = "杭州";
		String fromStation ="BJP";
		String toStation = "HZH";
		String trainDate ="2017-09-01";
		String cheCi ="G35";
		String seatType ="edz";
		JSONArray passengers = new JSONArray();
		JSONObject passenger = new  JSONObject();
		passenger.put("contactName", "");//乘车人名
		passenger.put("idCardInfo", "");//证件号
		passenger.put("idCardType", "1");
		passengers.add(passenger);
		String contact ="张三";
		String phone = "15110020101";
		String submit = submit(Cookie, fromStationName, toStationName, fromStation,toStation,trainDate, cheCi, seatType, passengers, contact, phone).toString();
		System.out.println(submit);
	}

	public static JSONObject submit(String Cookie, String fromStationName, String toStationName, String fromStation,String toStation,String trainDate,
			String cheCi, String seatType, JSONArray passengers, String contact, String phone) {
		JSONObject res = new JSONObject();
		String msg = "";
		boolean success = true;
		String responseTicket = searchTickets(Cookie, fromStationName, toStationName, trainDate, fromStation,
				toStation);
		
		System.out.println(responseTicket);
		if (Utils.isEmpty(responseTicket)) {
			msg = "查询余票失败";
			success = false;
			res.put("msg", msg);
			res.put("success", success);
			return res;
		}
		try {
			JSONObject object = JSONObject.parseObject(responseTicket);
			boolean successObject = object.getBooleanValue("success");
			if (!successObject) {
				res.put("msg", "查询余票失败");
				res.put("success", false);
				return res;
			}
			JSONArray tickets = object.getJSONArray("tickets");
			if (null == tickets || tickets.isEmpty()) {
				res.put("msg", cheCi + "不存在");
				res.put("success", false);
				return res;
			}
			
			JSONObject needTicket = new JSONObject();
			// 查找对应需要预定提交的车次
			for (int i = 0; i < tickets.size(); i++) {
				JSONObject ticket = tickets.getJSONObject(i);
				JSONObject trainInfo = ticket.getJSONObject("trainInfo");
				String trainCode = trainInfo.getString("trainCode");
				if (trainCode.equals(cheCi)) {
					needTicket = ticket;
					break;
				}
			}
			if (needTicket.isEmpty()) {
				res.put("msg", cheCi + "不存在");
				res.put("success", false);
				return res;
			}
			// 获取本车次的坐席
			String prices = "";
			JSONArray seatList = needTicket.getJSONArray("seatList");
			for (int i = 0; i < seatList.size(); i++) {
				JSONObject seat = seatList.getJSONObject(i);
				String name = seat.getString("name");
				String type = seat.getString("type");
				float price = seat.getFloatValue("price");
				int num = seat.getIntValue("num");
				if (type.equals(seatType)) {
					if (num == 0) {
						res.put("msg", cheCi + "坐席：" + name + "无票");
						res.put("success", false);
						return res;
					}
					prices = price * 100 + "";
					break;
				}
			}
			if (Utils.isEmpty(prices)) {
				res.put("msg", cheCi + "没有你要的坐席");
				res.put("success", false);
				return res;
			}
			String trainTime = needTicket.getJSONObject("trainInfo").getString("startTime");
			
			String fromStationCode =  needTicket.getJSONObject("trainInfo").getString("fromStationCode");
			String toStationCode =  needTicket.getJSONObject("trainInfo").getString("toStationCode");

			// 获取乘客列表
			String responsePassengers = searchPassengers(Cookie);
			// 循环判断乘客列表是否存在此乘客
			JSONObject passengersObject = JSONObject.parseObject(responsePassengers);
			JSONArray passengerList = passengersObject.getJSONArray("passengerList");
			String passengerIds = "";
			for (int i = 0; i < passengerList.size(); i++) {
				String contactName = passengerList.getJSONObject(i).getString("contactName");
				String contactId = passengerList.getJSONObject(i).getString("contactId");
				for (int j = 0; j < passengers.size(); j++) {
					String name = passengers.getJSONObject(j).getString("contactName");
					if (contactName.equals(name)) {
						passengerIds += contactId + ",";
						passengers.remove(j);
						continue;
					}
				}
			}
			// 添加乘客
			if (!passengers.isEmpty()) {
				for (int i = 0; i < passengers.size(); i++) {
					String addRespose = addPassenger(Cookie, passengers.getJSONObject(i).getString("contactName"),
							passengers.getJSONObject(i).getString("idCardInfo"),
							passengers.getJSONObject(i).getString("idCardType"));
					if (Utils.isEmpty(addRespose)) {
						res.put("msg", "添加乘客失败");
						res.put("success", false);
						return res;
					}

					JSONObject parseObject = JSONObject.parseObject(addRespose);
					if (!parseObject.getBooleanValue("success")) {
						res.put("msg", "添加乘客失败");
						res.put("success", false);
						return res;
					}

					String passengerId = parseObject.getString("passengerId");
					passengerIds += passengerId + ",";
				}

			}
			// 拼接要提交的乘客
			passengerIds = passengerIds.substring(0, passengerIds.length() - 1);
			// 添加联系人
			String addContentRespose = addContact(Cookie, contact, phone);
			JSONObject contentObject = JSONObject.parseObject(addContentRespose);
			if (Utils.isEmpty(addContentRespose) || !contentObject.getBooleanValue("success")) {
				res.put("msg", "添加联系人失败");
				res.put("success", false);
				return res;
			}
			String contactId = contentObject.getString("contactId");
			String insuranceCode = "0";
			String hasInvoice = "false";
			String isGrab = "false";
			String acceptNoSeat = "0";
			submit(Cookie, cheCi, seatType, "1", prices, fromStationCode, fromStationName, toStationCode,
					toStationName, trainDate, trainTime, passengerIds, contactId, contact, phone, "0", "",
					"", "false", insuranceCode, hasInvoice, isGrab, acceptNoSeat);
			
			
			
			


		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 添加联系人
	 * 
	 * @param cookie
	 * @param contact
	 * @param phone
	 * @return
	 */
	private static String addContact(String cookie, String contact, String phone) {
		String param;
		try {
			param = "contactName=" + URLEncoder.encode(contact, "UTF-8") + "&contactPhone=" + phone;
			String ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
			String ContentLength = param.length() + "";
			String Referer = "";
			Map<String, String> header = RequestUtil.getRequestHeader(cookie, Referer, ContentType, ContentLength,
					false, false, false);
			String searchResposne = RequestUtil.post(addContact, param, RequestUtil.UTF8, header, 0, null);
			System.out.println(searchResposne);
			return searchResposne;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 添加乘客
	 * 
	 * @param contactName
	 * @param idCardInfo
	 * @param idCardType
	 * @return
	 */
	private static String addPassenger(String cookie, String contactName, String idCardInfo, String idCardType) {
		String param;
		try {
			param = "contactName=" + URLEncoder.encode(contactName, "UTF-8") + "&idCardType=" + idCardType
					+ "&idCardInfo=" + idCardInfo;
			String ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
			String ContentLength = param.length() + "";
			String Referer = "";
			Map<String, String> header = RequestUtil.getRequestHeader(cookie, Referer, ContentType, ContentLength,
					false, false, false);
			String searchResposne = RequestUtil.post(addPassengerUrl, param, RequestUtil.UTF8, header, 0, null);
			System.out.println(searchResposne);
			return searchResposne;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 获取乘客列表
	 * 
	 * @param cookie
	 * @return
	 */
	private static String searchPassengers(String cookie) {
		String param = "passengerType=1";
		String ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
		String ContentLength = param.length() + "";
		String Referer = "";
		Map<String, String> header = RequestUtil.getRequestHeader(cookie, Referer, ContentType, ContentLength, false,
				false, false);
		String searchResposne = RequestUtil.post(passengerUrl, param, RequestUtil.UTF8, header, 0, null);
		return searchResposne;
	}


	/**
	 * 查询余票
	 * 
	 * @param cookie
	 * @param fromStationName
	 * @param toStationName
	 * @param trainDate
	 * @param fromStation
	 * @param toStation
	 * @return
	 */
	private static String searchTickets(String cookie, String fromStationName, String toStationName, String trainDate,
			String fromStation, String toStation) {
		String param;
		try {
			param = "ticketRequest.trainDate=" + trainDate + "&ticketRequest.fromStation=" + fromStation
					+ "&ticketRequest.toStation=" + toStation + "&ticketRequest.fromStationName="
					+ URLEncoder.encode(fromStationName, "UTF-8") + "&ticketRequest.toStationName="
					+ URLEncoder.encode(toStationName, "UTF-8") + "&operateType=&orderId=&subOrderIds=";
			String ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
			String ContentLength = param.length() + "";
			String Referer = "";
			Map<String, String> header = RequestUtil.getRequestHeader(cookie, Referer, ContentType, ContentLength,
					false, false, false);
			String searchResposne = RequestUtil.post(searchTicketsUrl, param, RequestUtil.UTF8, header, 0, null);
			return searchResposne;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void submit(String Cookie, String cheCi, String seatType, String ticketType, String seatPrice,
			String fromStationCode, String fromStationName, String toStationCode, String toStationName,
			String trainDate, String trainTime, String passengerIds, String contactId, String contact, String phone,
			String realBook, String account, String password, String hasInsurance, String insuranceCode,
			String hasInvoice, String isGrab, String acceptNoSeat) {
		String param;
		try {
			param = "cheCi=" + cheCi + "&seatType=" + seatType + "&ticketType=" + ticketType + "&seatPrice=" + seatPrice
					+ "&fromStationCode=" + fromStationCode + "&fromStationName="
					+ URLEncoder.encode(fromStationName, "UTF-8") + "&toStationCode=" + toStationCode
					+ "&toStationName=" + URLEncoder.encode(toStationName, "UTF-8") + "&trainDate=" + trainDate
					+ "&trainTime=" + URLEncoder.encode(trainTime, "UTF-8") + "&passengerIds=" + passengerIds
					+ "&contactId=" + contactId + "&contact=" + URLEncoder.encode(contact, "UTF-8") + "&phone=" + phone
					+ "&realBook=" + realBook + "&account=" + account + "&password=" + password + "&hasInsurance="
					+ hasInsurance + "&insuranceCode=" + insuranceCode + "&hasInvoice=" + hasInvoice
					+ "&invoiceJson=%7B%7D" + "&isGrab=" + isGrab + "&acceptNoSeat=" + acceptNoSeat + "&userRank="
					+ "&deadline=";
			String ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
			String ContentLength = param.length() + "";
			String Referer = "";
			Map<String, String> header = RequestUtil.getRequestHeader(Cookie, Referer, ContentType, ContentLength,
					false, false, false);
			String submitResposne = RequestUtil.post(submitJDOrderUrl, param, RequestUtil.UTF8, header, 0, null);
			System.out.println(submitResposne);
			JSONObject parseObject = JSONObject.parseObject(submitResposne);
			Boolean success = parseObject.getBoolean("success");
			if (success) {
				String orderId = parseObject.getString("orderId");
				for (int i = 0; i < 2000; i++) {
					bookResult(Cookie, orderId);
					sleep(5000L);
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}

	private static void bookResult(String Cookie, String orderId) {
		String param = "orderId=" + orderId;
		String ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
		String ContentLength = param.length() + "";
		String Referer = "";
		Map<String, String> header = RequestUtil.getRequestHeader(Cookie, Referer, ContentType, ContentLength, false,
				false, false);
		String bookResultRespose = RequestUtil.post(bookResultUrl, param, RequestUtil.UTF8, header, 0, null);
		System.out.println(bookResultRespose);
	}

	private static void sleep(long i) {
		try {
			Thread.sleep(i);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
